package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    public boolean isAdmin() {
        try {
            String requestURI = request.getRequestURI();
            if(requestURI.startsWith("/member")){
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建时间
        if (metaObject.hasSetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        }

        // 更新时间（插入时通常与创建时间相同）
        if (metaObject.hasSetter("updateTime")) {
            this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        }

        if(isAdmin()) {
            // 创建人
            if (metaObject.hasSetter("createBy")) {
                this.strictInsertFill(metaObject, "createBy", String.class, loadUserId());
            }

            // 更新人（插入时通常与创建人相同）
            if (metaObject.hasSetter("updateBy")) {
                this.strictInsertFill(metaObject, "updateBy", String.class, loadUserId());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时间
        if (metaObject.hasSetter("updateTime")) {
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        }

        if(isAdmin()) {
            // 更新人
            if (metaObject.hasSetter("updateBy")) {
                this.strictUpdateFill(metaObject, "updateBy", String.class, loadUserId());
            }
        }
    }


    /**
     * 获取当前登录人的ID
     *
     * @return
     */
    private static String loadUserId() {

        //获取当前登录人的id
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (ObjectUtils.isNotEmpty(loginUser)) {
                return loginUser.getUserId().toString();
            }
            return 1L + "";
        } catch (Exception e) {
            return 1L + "";
        }
    }
}